﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FMODNet;
using FMOD;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace FMODNET.Sample
{
    public class Fader : DSPBase
    {
        public override string Name
        {
            get
            {
                return "Fader";
            }
        }
        protected override void loadParameters()
        {
            Settings = new List<DSPSetting>();
        }
        int __length = 0;
        int startPosition;
        public int CurrentPosition
        { get; set; }
        public Fader(int startPosition, int soundLength, SoundDevice device) : base(device)
        {
            this.startPosition = startPosition;
            __length = soundLength;
        }
        float stepsToStartFade;
        float initialVolume = 1.0f;
        public override RESULT OnRead(IntPtr input, IntPtr output, int inChannels, int outChannels, uint length)
        {
            uint count;
            int count2;
            bool needsFade = CurrentPosition >= this.startPosition;

            if (!fadeCalculated && needsFade)
            {
                this.Enqueue(() =>
                {

                    if (fadeCalculated && !needsFade)
                        return;
                    Trace.WriteLine("Calculating fade");
                    stepsToStartFade = initialVolume / ((float)(this.__length - CurrentPosition));
                    stepsToStartFade *= 23.0f;
                    fadeCalculated = true;
                    Trace.WriteLine(string.Format("Steps in ms: {1}. Volume: {0}, length: {2}, CurrentPosition: {3}", stepsToStartFade, (this.__length - CurrentPosition), this.__length, CurrentPosition));
                    
                }, true);

            }
            else
            {
                this.initialVolume -= this.stepsToStartFade;
                if (initialVolume <= 0)
                    initialVolume = 0;
            }
            unsafe
            {
                float* inbuffer = (float*)input.ToPointer();
                float* outbuffer = (float*)output.ToPointer(); 
                for (count = 0; count < length; count++)
                    for (count2 = 0; count2 < outChannels; count2++) 
                        outbuffer[(count * outChannels) + count2] = inbuffer[(count * inChannels) + count2] * (fadeCalculated ? initialVolume : 1.0f);
            }
            return FMOD.RESULT.OK;
        }
        bool fadeCalculated = false;
    }
}